﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Clinica_Frba.NewFolder8;
using System.Data.SqlClient;

namespace Clinica_Frba.Generar_Receta
{
    public partial class AltaRecetas : Form
    {
        private AgregarMedicamento AgregarMedicamentoForm = null;
        protected InfoDeAfiliado afiliadoSeleccionado;
        private String idTurno = null;
        private String idProfesional = null;
        private string[] bonosId = new string[0];
        private bool recargando = false;

        public AltaRecetas(String idTurno)
        {
            InitializeComponent();
            this.idTurno = idTurno;
            calcularIdProfesionalPorIdTurno(idTurno);
            calcularAfiliadoPorIdTurno(idTurno);
            cargarBonosFarmacia();
        }

        private void calcularIdProfesionalPorIdTurno(string idTurno)
        {
            SqlConnection myConnection = new SqlConnection(publico.ConnectionString);
            myConnection.Open();
            SqlCommand consulta = new SqlCommand("SELECT ID_PROF FROM TURNO T WHERE T.ID_TURNO = " + idTurno + "; ", myConnection);
            SqlDataReader executeCMD = consulta.ExecuteReader();
            executeCMD.Read();

            idProfesional = executeCMD["ID_PROF"].ToString();
        }

        private void cargarBonosFarmacia()
        {
            recargando = true;
            button4.Enabled = false;

            try
            {
                checkedListBox1.DataSource = LoadBonoFarmaciaDataTable();
                checkedListBox1.DisplayMember = "Fecha_Compra";
                checkedListBox1.ValueMember = "Id";

                marcarItemsSeleccionados();
            }
            finally
            {
                recargando = false;
                button4.Enabled = true;
            }
        }

        private void marcarItemsSeleccionados()
        {
            for (int i = 0; i < checkedListBox1.Items.Count; i++)
            {
                DataRowView item = (DataRowView)checkedListBox1.Items[i];

                string itemValue = ((string)item.Row["Id"].ToString());
                if (bonosId.Contains(itemValue))
                {
                    checkedListBox1.SetItemChecked(i, true);
                }
            }
        }

        public DataTable LoadBonoFarmaciaDataTable()
        {

            string comando = "select B.ID_BONO AS Id, B.Fecha_Compra as Fecha_Compra from BONO_FARMACIA B, BONO_COMPRA BC, COMPRA C WHERE B.ID_BONO = BC.ID_BONO_F AND BC.ID_COMPRA = C.ID_COMPRA AND B.USADO = 'N' AND LEFT(C.ID_AFIL, 7) = LEFT('" + this.afiliadoSeleccionado.strAfiliadoID + "', 7) order by B.Fecha_Compra asc";
            System.Data.SqlClient.SqlConnection myConnection = new System.Data.SqlClient.SqlConnection(publico.ConnectionString);
            myConnection.Open();
            System.Data.SqlClient.SqlDataAdapter da = new System.Data.SqlClient.SqlDataAdapter(comando, myConnection);
            DataTable dt = new DataTable();

            da.Fill(dt);

            return dt;
        }

        private void calcularAfiliadoPorIdTurno(string idTurno)
        {
            InfoDeAfiliado info = new InfoDeAfiliado();
            SqlConnection myConnection = new SqlConnection(publico.ConnectionString);
            myConnection.Open();
            SqlCommand consulta = new SqlCommand("SELECT top 1 * FROM AFILIADO af LEFT JOIN PLAN_MEDICO pm ON pm.ID_PLAN = af.ID_PLAN  WHERE af.ID_AFIL = (SELECT top 1 T.ID_AFIL FROM TURNO T WHERE T.ID_TURNO = '" + idTurno + "') ", myConnection);
            SqlDataReader executeCMD = consulta.ExecuteReader();
            executeCMD.Read();

            info.strAfiliadoID = executeCMD["ID_AFIL"].ToString();
            info.strCantidadDeFamiliaresDependientes = executeCMD["RELATIVOS_A_CARGO"].ToString();
            info.strNombre = executeCMD["Nombre"].ToString();
            info.strApellido = executeCMD["Apellido"].ToString();
            info.strEmail = executeCMD["mail"].ToString();
            info.strEstadoCivil = executeCMD["ESTADO_CIVIL"].ToString();
            info.strDireccion = executeCMD["Direccion"].ToString();
            info.strPlanMedico = executeCMD["descripcion"].ToString();
            info.strSexo = executeCMD["Sexo"].ToString();
            info.strTelefono = executeCMD["Telefono"].ToString();
            info.strNumeroDeDocumento = executeCMD["NRO_DOC"].ToString();
            info.strTipoDeDocumento = executeCMD["TIPO_DOC"].ToString();
            info.strFechaDeNacimiento = executeCMD["FECHA_NACIMIENTO"].ToString();


            executeCMD.Close();

            setAfiliadoSeleccionado(info);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (dataGridView1.Rows.Count % 5 == 0 )
            {
                if (dataGridView1.Rows.Count == 0 && getCountBonos() == 0)
                {
                    Dialogos.MostrarMessageDialog("Para agregar medicamentos necesita seleccionar un bono de farmacia ");
                    return;
                }
                if (dataGridView1.Rows.Count / 5 >= getCountBonos())
                {
                    Dialogos.MostrarMessageDialog("Para agregar mas de " + dataGridView1.Rows.Count + " medicamentos necesita agregar un bono de farmacia adicional");
                    return;
                }
            }


            if (AgregarMedicamentoForm == null)
            {

                AgregarMedicamentoForm = new AgregarMedicamento();
                AgregarMedicamentoForm.DataGridViewRows = this.dataGridView1.Rows;
                AgregarMedicamentoForm.FormClosing += AgregarMedicamento_FormClosing;
                AgregarMedicamentoForm.ShowDialog(this);
                //AgregarMedicamentoForm.Show();
                
            }
            else
            {
                Dialogos.MostrarMessageDialog("Ya se encuentra agregando un medicamento en otra ventana");
            }
        }

        private int getCountBonos()
        {
            return bonosId.Length;
        }

        private void AgregarMedicamento_FormClosing(object sender, EventArgs e)
        {

            if (AgregarMedicamentoForm.isAccepted())
            {
                string seleccionado = AgregarMedicamentoForm.GetMedicamentoSeleccionado();

                    DataGridViewRow row = (DataGridViewRow)this.dataGridView1.RowTemplate.Clone();
                    row.CreateCells(this.dataGridView1, new object[] { AgregarMedicamentoForm.GetIdSeleccionado(), seleccionado, AgregarMedicamentoForm.GetCantidadSeleccionada(), cantidadSeleccionadaEnLetras(AgregarMedicamentoForm.GetCantidadSeleccionada()), "Borrar" });

                    this.dataGridView1.Rows.Add(row);
                

            }

            AgregarMedicamentoForm = null;
        }

        private object cantidadSeleccionadaEnLetras(string p)
        {
            if (p != null)
            {
                if (p.Equals("1"))
                {
                    return "Uno";
                }
                if (p.Equals("2"))
                {
                    return "Dos";
                }
                if (p.Equals("3"))
                {
                    return "Tres";
                }
            }

            return "";
        }

        private void button3_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void AltaRecetas_Load(object sender, EventArgs e)
        {
            //this.dataGridView1.AutoGenerateDeleteButton = true;
        }

        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (dataGridView1.Columns[e.ColumnIndex] is DataGridViewButtonColumn && e.RowIndex != -1)
            {
                dataGridView1.Rows.RemoveAt(e.RowIndex);
            }
        }
        #region FormBusquedaAfiliadoRecetaParent Members

        void setAfiliadoSeleccionado(InfoDeAfiliado info)
        {
            this.afiliadoSeleccionado = info;
            if (afiliadoSeleccionado != null)
            {
                this.textBox1.Text = afiliadoSeleccionado.strApellido + ", " + afiliadoSeleccionado.strNombre + " (Afiliado: " + afiliadoSeleccionado.strAfiliadoID + ")";
                habilitarBotones();
            }
            else
            {
                this.textBox1.Text = "";
                desHabilitarBotones();
            }
        }

        private void desHabilitarBotones()
        {
            this.button1.Enabled = false;
            this.button2.Enabled = false;
        }

        private void habilitarBotones()
        {
            this.button1.Enabled = true;
            this.button2.Enabled = true;
        }

        #endregion

        private void button2_Click(object sender, EventArgs e)
        {
            if (Dialogos.MostrarYesNoDialog("Seguro que desea guardar esta receta?"))
            {
                SqlConnection myConnection = new System.Data.SqlClient.SqlConnection(publico.ConnectionString);
                myConnection.Open();

                //bono_id : *
                /*
                SqlCommand sqlCommand0 = new SqlCommand("select TOP 1 b.id_bono from BONO_FARMACIA B, BONO_COMPRA BC, COMPRA C WHERE B.ID_BONO = BC.ID_BONO_F AND BC.ID_COMPRA = C.ID_COMPRA AND B.USADO = 'N' AND C.ID_AFIL = '" + afiliadoSeleccionado.strAfiliadoID + "'", myConnection);
                int bonoId = (int) sqlCommand0.ExecuteScalar();*/

                string strQuery = "insert into RECETA values ((select top 1 id_RECETA from receta order by id_receta desc) + 1, '" + afiliadoSeleccionado.strAfiliadoID + "', " + idProfesional + ", " + idTurno + ", 'H');";

                int bonoCounter = 0;
                int medicamentoCounter = 0;
                HashSet<string> bonosUsados = new HashSet<string>();
                foreach (DataGridViewRow row in dataGridView1.Rows)
                {
                    string bonoAUsar = bonosId[bonoCounter];
                    bonosUsados.Add(bonoAUsar);
                    strQuery += "INSERT INTO MEDICAMENTO_BONO VALUES (" + (row.Cells["Id"].Value) + ", " + bonoAUsar + ", " + row.Cells["Cantidad"].Value  + ");"; //agregar cantidad
                    medicamentoCounter++;
                    if (medicamentoCounter % 5 == 0)
                    {
                        bonoCounter++;
                    }
                }

                string fechaat = publico.fecha;
                string currentDate = "CONVERT(datetime,'" + fechaat + "',103)";

                
                foreach(string bonoId in bonosUsados)
                {
                    strQuery += "UPDATE BONO_FARMACIA SET ID_RECETA = (select top 1 id_RECETA from receta order by id_receta desc) , USADO = 'S', FECHA_PRESCRIPCION = " + currentDate + " where id_bono = " + bonoId + ";";
                }
                
                strQuery = "BEGIN TRANSACTION;" + strQuery + "COMMIT TRANSACTION;";

                SqlCommand sqlCommand = new SqlCommand(strQuery, myConnection);
                int executeCMD = sqlCommand.ExecuteNonQuery();

                if (executeCMD > 0)
                {
                    Dialogos.MostrarMessageDialog("Se creo la Receta");
                    this.Close();
                }
                else
                {
                    Dialogos.MostrarMessageDialog("Se produjo un error al guardar la receta");
                }
            }
        }

        private void bonosFarmaciaSeleccionadoChanged(object sender, EventArgs e)
        {
            if (!recargando)
            {

                bonosId = new string[checkedListBox1.CheckedItems.Count];
                for (int i = 0; i < checkedListBox1.CheckedItems.Count; i++)
                {
                    object item = checkedListBox1.CheckedItems[i];
                    bonosId[i] = ((DataRowView)item).Row["Id"].ToString();
                }

            }

        }

        private void button4_Click(object sender, EventArgs e)
        {
            cargarBonosFarmacia();
        }


    }
}
